<template>
  <div class="app-container">
    <div class="filter-container" id="filter-container-MhUnit">
      <el-input
        v-model="listQuery.name"
        size="small"
        placeholder="单位名称"
        style="width: 200px; "
        class="filter-item"
        @keyup.enter.native="handleFilter"
        clearable
      />
      <el-input
        v-model="listQuery.account"
        size="small"
        placeholder="账号"
        style="width: 200px; "
        class="filter-item"
        @keyup.enter.native="handleFilter"
        clearable
      />
      <!--<el-input
          v-model="listQuery.legalPerson"
          size="small"
          placeholder="法人代表"
          style="width: 200px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
          clearable
      />
      <el-input
          v-model="listQuery.bizLicenseSignpic"
          size="small"
          placeholder="社会信用统一代码证"
          style="width: 200px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
          clearable
      />-->
      <select-option
          v-model="listQuery.status"
          size="small"
          placeholder="审核状态"
          style="width: 200px; "
          class="filter-item"
          :clearable=true
          prop-name="AuditStatus"
          :prop-ds-type=1
          prop-url="/citymh/enum/getData4AddBy"
      />
     <!-- <el-input
          v-model="listQuery.id"
          size="small"
          placeholder="ID"
          style="width: 200px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
          clearable
      />-->

     <!-- <el-input
          v-model="listQuery.password"
          size="small"
          placeholder="密码"
          style="width: 200px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
          clearable
      />
      <el-input
          v-model="listQuery.linkman"
          size="small"
          placeholder="联系人"
          style="width: 200px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
          clearable
      />-->
     <!-- <el-input
          v-model="listQuery.telephone"
          size="small"
          placeholder="手机"
          style="width: 200px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
          clearable
      />
      <el-input
          v-model="listQuery.phone"
          size="small"
          placeholder="电话"
          style="width: 200px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
          clearable
      />
      <el-input
          v-model="listQuery.fax"
          size="small"
          placeholder="传真"
          style="width: 200px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
          clearable
      />
      <el-input
          v-model="listQuery.email"
          size="small"
          placeholder="邮箱"
          style="width: 200px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
          clearable
      />
      <select-option
          v-model="listQuery.deleteflag"
          size="small"
          placeholder="删除标志"
          style="width: 200px; "
          class="filter-item"
          :clearable=true
          prop-name="Deleteflag"
          :prop-ds-type=1
          prop-url="/citymh/enum/getData4AddBy"
      />-->
      <el-date-picker
          v-model="listQuery.createdate"
          type="daterange"
          value-format="yyyy-MM-dd"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="创建日期:开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          size="small"
          class="filter-item"
          clearable
      />
      <el-button :loading="queryLoading" class="filter-item" size="small" type="primary" plain icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <!--<el-button v-if="hasDownloadBtn" :loading="downloadLoading" class="filter-item" size="small" type="primary" plain icon="el-icon-download" @click="handleDownload">
        导出报表
      </el-button>-->
<!--      <el-button v-if="hasAddBtn" v-show="hasPermission(['mhUnit:create'])" class="filter-item" size="small" type="primary" plain icon="el-icon-plus" @click="handleCreate">
        添加
      </el-button>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      :show-summary="false"
      :summary-method="getSummaries"
      style="width: 100%;"
      :height="tableHeight"
      @sort-change="sortChange"
      @row-click="handleRowClick"
    >
      <!-- 行展开，显示的详细信息 -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="单位名称" >
              <span>{{ props.row.name }}</span>

            </el-form-item>
            <el-form-item label="法人代表" >
              <span>{{ props.row.legalPerson }}</span>

            </el-form-item>
            <el-form-item label="账号" >
              <span>{{ props.row.account }}</span>

            </el-form-item>
            <!--<el-form-item label="密码" >
              <span>{{ props.row.password }}</span>

            </el-form-item>-->
            <el-form-item label="社会信用统一代码证" >
              <span>{{ props.row.bizLicenseSignpic }}</span>

            </el-form-item>
            <el-form-item label="审核状态" >
              <span>{{ props.row.status|getJsonName }}</span>

            </el-form-item>
            <el-form-item label="联系人" >
              <span>{{ props.row.linkman }}</span>

            </el-form-item>
            <el-form-item label="联系电话" >
              <span>{{ props.row.telephone }}</span>

            </el-form-item>
           <!-- <el-form-item label="ID" >
              <span>{{ props.row.id }}</span>

            </el-form-item>-->
            <!--<el-form-item label="电话" >
              <span>{{ props.row.phone }}</span>

            </el-form-item>
            <el-form-item label="传真" >
              <span>{{ props.row.fax }}</span>

            </el-form-item>
            <el-form-item label="邮箱" >
              <span>{{ props.row.email }}</span>

            </el-form-item>
            <el-form-item label="删除标志" >
              <span>{{ props.row.deleteflag|getJsonName }}</span>

            </el-form-item>
            <el-form-item label="修改日期" >
              <span>{{ props.row.modifydate }}</span>

            </el-form-item>
            <el-form-item label="创建人" >
              <span>{{ props.row.createman }}</span>

            </el-form-item>
            <el-form-item label="修改人" >
              <span>{{ props.row.modifyman }}</span>

            </el-form-item>-->
            <el-form-item label="创建日期" >
              <span>{{ props.row.createdate }}</span>

            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column
        label="单位名称"
        prop="name"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="法人代表"
        prop="legalPerson"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
          <span>{{ row.legalPerson }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="账号"
        prop="account"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
          <span>{{ row.account }}</span>
        </template>
      </el-table-column>


      <el-table-column
        label="联系人"
        prop="linkman"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
          <span>{{ row.linkman }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="联系电话"
        prop="telephone"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
          <span>{{ row.telephone }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="审核状态"
        prop="status"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
          <span>{{ row.status|getJsonName }}</span>
        </template>
      </el-table-column>


      <el-table-column
        label="电话"
        prop="phone"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="社会信用统一代码证"
        prop="bizLicenseSignpic"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
          <span>{{ row.bizLicenseSignpic }}</span>
        </template>
      </el-table-column>

      <!--操作Button + 页面级权限控制:hasPermission -->
      <el-table-column v-if="hasEditBtn || hasDelBtn"  v-show="hasPermission(['mhUnit:update','mhUnit:delete'])" fixed="right" label="操作" align="center" min-width="130">
        <template slot-scope="{row,$index}">
          <el-button v-if="hasEditBtn" v-show="hasPermission(['mhUnit:update'])" type="primary" icon="el-icon-edit" title="编辑审核" size="mini" @click="handleUpdate(row)">
          </el-button>
          <el-button v-if="hasDelBtn" v-show="hasPermission(['mhUnit:delete'])" type="danger" icon="el-icon-delete" title="删除" size="mini" @click="handleDelete(row)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <form-details ref="formDetails" :row="row" :isModule="true" @createResult="createResult" @updateResult="updateResult"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {fetchList, deleteApi} from './api'
import waves from '@/directive/waves' // waves directive
import { parseTime, reorgQueryParams, resizeTableHeight } from '@/utils'
import checkPermission from '@/utils/permission'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import FormDetails from './form-details.vue' // add form form dialog
// 从当前View的私有数据对象中取数据
import { pickerOptions, pickerOptionsSingleDate } from './data'
// 导入多选项组件
import SelectOption from '@/views/coding/components/SelectOption'

export default {
    name: 'MhUnit-List',

    components: { Pagination, FormDetails, SelectOption },
    directives: {waves},

    props: {
        // 作为子组件时，需要回调传值；应用场景：一对多关联查询时，点击左边查询列表，传值给右边子列表，查询子列表结果
        isModule: {
            type: Boolean,
            default: false
        },
        // 当作为侧边查询结果显示的右子组件时，接收父组件的传值，watch中查询
        parentRow: Object
    },

    filters: {
        statusFilter(status) {
            const statusMap = {
                published: 'success',
                draft: 'info',
                deleted: 'danger'
            }
            return statusMap[status]
        }
    },

    data() {
        return {
            tableKey: 0,
            btnIdList: [1, 2, 3, 4, 5],
            list: [],
            total: 0,
            footer: [],
            listLoading: false,
            queryLoading: false,
            downloadLoading: false,
            listQuery: {
                page: 1,
                limit: 20
            },
            importanceOptions: [1, 2, 3],
            sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
            statusOptions: ['published', 'draft', 'deleted'],
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: '编辑审核',
                create: '新增'
            },
            pickerOptions: pickerOptions,
            pickerOptionsSingleDate: pickerOptionsSingleDate,
            statusList: [], // 多选项列表
            deleteflagList: [], // 多选项列表
            row: {},
            tableHeight:0, // 表格高度
            filterContainerHeight: 0, // 查询容器高度
            clientHeight: 0 // 浏览器高度
        }
    },
    computed: {
        // button is show
        hasAddBtn() {
          if ( this.btnIdList.filter(id=>id===1).length!=0 ) {
            return true
          }
          return false
        },
        hasEditBtn() {
          if ( this.btnIdList.filter(id=>id===2).length!=0 ) {
            return true
          }
          return false
        },
        hasDelBtn() {
          if ( this.btnIdList.filter(id=>id===3).length!=0 ) {
            return true
          }
          return false
        },
        hasDownloadBtn() {
          if ( this.btnIdList.filter(id=>id===4).length!=0 ) {
            return true
          }
          return false
        }
    },

    watch: {
        // 当作为侧边查询的子组件时，接收父组件的传值，watch中查询
        parentRow(pRow) {
            this.listQuery[pRow.classInstance+'Id'] = pRow.id // parantId, 需修改成主表ID。******
            this.handleFilter()
        }
    },

    created() {
        this.getList()
    },

    mounted () {
        // 浏览器、元素大小变化时，动态调整table高度
        resizeTableHeight(this, 'filter-container-MhUnit')
    },

    methods: {
        // 页面级权限控制，调用方法如：hasPermission(['a2user:delete'])
        hasPermission(needPermisions) {
          return checkPermission(needPermisions)
        },
        // 刷新
        getList() {
            this.queryLoading = true
            this.listLoading = true
            // 重组查询条件
            const params = Object.assign({}, this.listQuery)
            reorgQueryParams(params)
            // 查询
            fetchList(params).then(result => {
                if (!result.success) {
                    this.notify(result)
                    this.queryLoading = false
                    this.listLoading = false
                    return
                }
                this.list = result.map.rows
                this.total = result.map.total
                // footer
                if (result.map.footer && result.map.footer.length>0) {
                    this.footer = result.map.footer
                }
                this.queryLoading = false
                this.listLoading = false
                ++this.tableKey
            })
        },
        // 从第一页开始查询
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        // 排序
        sortChange(data) {
            const { prop, order } = data
            if (prop === 'id') {
                this.sortByID(order)
            }
        },
        sortByID(order) {
            if (order === 'ascending') {
                this.listQuery.sort = '+id'
            } else {
                this.listQuery.sort = '-id'
            }
            this.handleFilter()
        },
        // SUM
        getSummaries(param) {
            if (this.footer.length == 0) {
                return []
            }
            const sums = [];
            const { columns, data } = param;
            columns.forEach((column, index) => {
                if (index === 1) {
                    sums[index] = '合计';
                    return;
                }
                if (this.footer[0][column.property] && typeof this.footer[0][column.property]!=="object") {
                    sums[index] = this.footer[0][column.property]
                    return;
                }
            });
            return sums;
        },
        // download excel
        handleDownload() {
            // 重组查询条件
            const params = Object.assign({}, this.listQuery)
            params.page = 1
            params.limit = 10000000
            reorgQueryParams(params)
            console.log(params)
            // 查询
            this.downloadLoading = true
            fetchList(params).then(result => {
                if (!result.success) {
                    this.notify(result)
                    this.downloadLoading = false
                    return
                }
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = ['Id', '名称', '创建时间', '创建人']  // excel中显示的列名
                    const filterVal = ['id', 'name', 'createdate', 'createman'] // excel中显示哪些列，与tHeader对应
                    const list = result.map.rows
                    const data = this.formatJson(filterVal, list)
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: 'excel',
                        autoWidth: true,
                        bookType: 'xlsx'
                    })
                    this.downloadLoading = false
                })
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else {
                    return v[j]
                }
            }))
        },
        // 添加操作 start
        handleCreate() {
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            // 消除上次出现的验证信息
            this.$nextTick(() => {
                this.$refs['formDetails'].clearValidate()
                this.$refs['formDetails'].resetTemp()
                this.$refs['formDetails'].defaultTemp()
            })
        },
        // 调用子组件操作数据
        createData() {
            this.$refs['formDetails'].createData()
        },
        // 子组件操作成功，回调此方法，关闭弹框、刷新
        createResult() {
            this.dialogFormVisible = false
            this.handleFilter()
        },
        // 编辑操作 start
        handleUpdate(row) {
            this.row = Object.assign({}, row) // copy obj
            this.row.status = this.row.status.id // 枚举对象，取id值
            this.row.deleteflag = this.row.deleteflag.id // 枚举对象，取id值
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            // 消除上次出现的验证信息
            this.$nextTick(() => {
                this.$refs['formDetails'].clearValidate()
            })
        },
        // 调用子组件操作数据
        updateData() {
            this.$refs['formDetails'].updateData()
        },
        // 子组件操作成功，回调此方法，关闭弹框、刷新
        updateResult() {
            this.dialogFormVisible = false
            this.getList()
        },
        // 删除操作
        handleDelete(row) {
            this.$confirm('确认删除吗？')
                  .then(_ => {
                      // delete api
                      deleteApi({ id: '' + row.id }).then((r) => {
                          this.notify(r)
                          if (r.success) {
                              this.getList()
                          }
                      })
                    // end
                  })
                  .catch(_ => {})
        },
        // 行点击事件；应用场景：一对多关联查询时，点击左边查询列表，传值给右边子列表，查询子列表结果 xxxxxx
        handleRowClick(row, column, event) {
            // 从父组件调用此方法，进行回调下
            if (this.isModule) {
                row.classInstance = 'mhUnit'
                this.$emit('input', row)
            }
        },
        getSortClass: function(key) {
            const sort = this.listQuery.sort
            return sort === `+{key}` ? 'ascending' : 'descending'
        }
    }
}
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 40%;
  }
</style>
